package cn.wolfcode.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.wolfcode.domain.Article;
import cn.wolfcode.domain.ArticleContent;
import cn.wolfcode.domain.ArticleType;
import cn.wolfcode.service.IArticleService;
import cn.wolfcode.service.IArticleTypeService;
import cn.wolfcode.vo.JSONMessage;

@Controller
@RequestMapping(value="/articles")
public class ArticleController {

	@Autowired
	private IArticleService articleService;
	
	@Autowired
	private IArticleTypeService articleTypeService;
	
	/**
	 * 进入文章管理界面
	 */
	@RequestMapping(value="/view")
	public String article() {
		return "article/article_view";
	}
	
	/**
	 * 获取文章列表数据
	 */
	@RequestMapping(value="")
	public String getArticleList(String articleTypeCode,Model model) {
		//如果文章分类编码为null，则查询所有文章列表
		List<Article> articleList;
		if(articleTypeCode == null) 
			articleList = articleService.getAll();
		else 
			articleList = articleService.getArticleByCode(articleTypeCode);
		
		model.addAttribute("articleList", articleList);
		//否则，则查询该文章分类下的文章列表
		return "article/article_list";
	}
	
	/**
	 * 新增文章界面
	 */
	@RequestMapping(value="/add")
	public String addView(Model model,Long id) {
		List<ArticleType> articleTypeList = articleTypeService.getArticleTypeList();
		model.addAttribute("articleTypeList", articleTypeList);
		if(id == null) {
			
			return "article/article_add";
		}else {
			Article article = articleService.getArticle(id);
			model.addAttribute("article", article);
			model.addAttribute("articleContent", article.getArticleContent());
			return "article/article_edit";
		}
	}
	
	
	/**
	 * 新增或者修改文章
	 */
	@RequestMapping(value="",method=RequestMethod.POST)
	@ResponseBody
	public JSONMessage save(Article article) {
		JSONMessage jSONMessage = new JSONMessage();
		try {
			articleService.save(article);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			jSONMessage.setErrmsg(e.getMessage());
		}
		return jSONMessage;
	}
	
	/**
	 * 通过文章id获取文章详细内容
	 */
	@RequestMapping(value="/{id}/content")
	@ResponseBody
	public String getContent(@PathVariable("id")Long articleId) {
		ArticleContent content = articleService.getContent(articleId);
		return content.getContent();
	}
}























